<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;

/**
 * 模型数据管理控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class VisitorController extends ThinkController{
	/**
     * 显示指定模型列表数据
     * @param  String $model 模型标识
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
	public function lists($model = null, $p = 0){
		$model || $this->error('模型名标识必须！');
		$page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

        //获取模型信息
        $model = M('Model')->getByName($model);
        $model || $this->error('模型不存在！');

        //解析列表规则
        $fields = array();
        $grids  = preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        foreach ($grids as &$value) {
        	if(trim($value) === ''){
        		continue;
        	}
            // 字段:标题:链接
        	$val      = explode(':', $value);
            // 支持多个字段显示
        	$field   = explode(',', $val[0]);
        	$value    = array('field' => $field, 'title' => $val[1]);
        	if(isset($val[2])){
                // 链接信息
        		$value['href']	=	$val[2];
                // 搜索链接信息中的字段信息
        		preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
        	}
        	if(strpos($val[1],'|')){
                // 显示格式定义
        		list($value['title'],$value['format'])    =   explode('|',$val[1]);
        	}
        	foreach($field as $val){
        		$array	=	explode('|',$val);
        		$fields[] = $array[0];
        	}
        }
        // 过滤重复字段信息
        $fields =   array_unique($fields);
        // 关键字搜索
        $map	=	array();
        $key	=	$model['search_key']?$model['search_key']:'title';
        if(isset($_REQUEST[$key])){
        	$map[$key]	=	array('like','%'.$_GET[$key].'%');
        	unset($_REQUEST[$key]);
        }
        // 条件搜索
        foreach($_REQUEST as $name=>$val){
        	if(in_array($name,$fields)){
        		$map[$name]	=	$val;
        	}
        }
        $row    = empty($model['list_row']) ? 10 : $model['list_row'];

        //读取模型数据列表
        if($model['extend']){
        	$name   = get_table_name($model['id']);
        	$parent = get_table_name($model['extend']);
        	$fix    = C("DB_PREFIX");

        	$key = array_search('id', $fields);
        	if(false === $key){
        		array_push($fields, "{$fix}{$parent}.id as id");
        	} else {
        		$fields[$key] = "{$fix}{$parent}.id as id";
        	}

        	/* 查询记录数 */
        	$count = M($parent)->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")->where($map)->count();

            // 查询数据
        	$data   = M($parent)
        	->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")
        	/* 查询指定字段，不指定则查询所有字段 */
        	->field(empty($fields) ? true : $fields)
                // 查询条件
        	->where($map)
        	/* 默认通过id逆序排列 */
        	->order("{$fix}{$parent}.id DESC")
        	/* 数据分页 */
        	->page($page, $row)
        	/* 执行查询 */
        	->select();

        } else {
        	if($model['need_pk']){
        		in_array('id', $fields) || array_push($fields, 'id');
        	}
        	$name = parse_name(get_table_name($model['id']), true);
        	$data = M($name)
        	/* 查询指定字段，不指定则查询所有字段 */
        	->field(empty($fields) ? true : $fields)
                // 查询条件
        	->where($map)
        	/* 默认通过id逆序排列 */
        	->order($model['need_pk']?'id DESC':'')
        	/* 数据分页 */
        	->page($page, $row)
        	/* 执行查询 */
        	->select();

        	/* 查询记录总数 */
        	$count = M($name)->where($map)->count();
        }

        //分页
        if($count > $row){
        	$page = new \Think\Page($count, $row);
        	$page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        	$this->assign('_page', $page->show());
        }

        $data   =   $this->parseDocumentList($data,$model['id']);
        $this->assign('model', $model);
        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->meta_title = $model['title'].'列表';
        $this->display($model['template_list']);
      }

      /**
     * 显示指定模型列表数据
     * @param  String $model 模型标识
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function viplists($model = null, $p = 0,$vip_type=null){
        $model || $this->error('模型名标识必须！');
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

        //获取模型信息
        $model = M('Model')->getByName($model);
        $model || $this->error('模型不存在！');

        //解析列表规则
        $fields = array();
        $grids  = preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        foreach ($grids as &$value) {
            if(trim($value) === ''){
                continue;
            }
            // 字段:标题:链接
            $val      = explode(':', $value);
            // 支持多个字段显示
            $field   = explode(',', $val[0]);
            $value    = array('field' => $field, 'title' => $val[1]);
            if(isset($val[2])){
                // 链接信息
                $value['href']  =   $val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
            }
            if(strpos($val[1],'|')){
                // 显示格式定义
                list($value['title'],$value['format'])    =   explode('|',$val[1]);
            }
            foreach($field as $val){
                $array  =   explode('|',$val);
                $fields[] = $array[0];
            }
        }
        // 过滤重复字段信息
        $fields =   array_unique($fields);
        // 关键字搜索
        $map    =   array();
        $key    =   $model['search_key']?$model['search_key']:'title';
        if(isset($_REQUEST[$key])){
            $map[$key]  =   array('like','%'.$_GET[$key].'%');
            unset($_REQUEST[$key]);
        }
        // 条件搜索
        foreach($_REQUEST as $name=>$val){
            if(in_array($name,$fields)){
                $map[$name] =   $val;
            }
        }
        $row    = empty($model['list_row']) ? 10 : $model['list_row'];
        //vipcode不为null
        $map['vipcode']=array('EXP','IS NOT NULL');
        $map['end_time']=array('EGT',time());
        $map['status']=1;
        if($vip_type){
            $map['vip_type']=$vip_type;
        }
        //读取模型数据列表
        if($model['extend']){
            $name   = get_table_name($model['id']);
            $parent = get_table_name($model['extend']);
            $fix    = C("DB_PREFIX");

            $key = array_search('id', $fields);
            if(false === $key){
                array_push($fields, "{$fix}{$parent}.id as id");
            } else {
                $fields[$key] = "{$fix}{$parent}.id as id";
            }

            /* 查询记录数 */
            $count = M($parent)->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")->where($map)->count();

            // 查询数据
            $data   = M($parent)
            ->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")
            /* 查询指定字段，不指定则查询所有字段 */
            ->field("visitor.*")
            ->join('vip_order on vip_order.visitor_id = visitor.id','left')
                // 查询条件
            ->where($map)
            /* 默认通过id逆序排列 */
            ->order("{$fix}{$parent}.id DESC")
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();

        } else {
            if($model['need_pk']){
                in_array('id', $fields) || array_push($fields, 'id');
            }
            $name = parse_name(get_table_name($model['id']), true);
            $data = M($name)
            /* 查询指定字段，不指定则查询所有字段 */
            ->field("visitor.*")
            ->join('vip_order on vip_order.visitor_id = visitor.id','left')
                // 查询条件
            ->where($map)
            // ->where(array('vip_order.status'=>1))
            /* 默认通过id逆序排列 */
            ->order($model['need_pk']?'id DESC':'')
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();

            /* 查询记录总数 */
            $count = M($name)
            ->join('vip_order on vip_order.visitor_id = visitor.id','left')
            ->where($map)
            ->count();
        }

        //分页
        if($count > $row){
            $page = new \Think\Page($count, $row);
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $this->assign('_page', $page->show());
        }

        $data   =   $this->parseDocumentList($data,$model['id']);
        //vip会员种类
        $viptypes = M('membership')->where(array('status'=>'0'))->select();
        $this->assign('model', $model);
        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->assign('vip_type', $vip_type);
        $this->assign('viptypes', $viptypes);
        $this->meta_title = $model['title'].'列表';
        $this->display('Visitor/vip_lists_common');
      }

      public function del($model = null, $ids=null){
      	$model = M('Model')->find($model);
      	$model || $this->error('模型不存在！');

      	$ids = array_unique((array)I('ids',0));

      	if ( empty($ids) ) {
      		$this->error('请选择要操作的数据!');
      	}

      	$Model = M(get_table_name($model['id']));
      	$map = array('id' => array('in', $ids) );
      	if($Model->where($map)->delete()){
      		$this->success('删除成功');
      	} else {
      		$this->error('删除失败！');
      	}
      }

    /**
     * 设置一条或者多条数据的状态
     * @author huajie <banhuajie@163.com>
     */
    public function setStatus($model='Document'){
    	return parent::setStatus($model);
    }
    
    public function edit($model = null, $id = 0){
        //获取模型信息
    	$model = M('Model')->find($model);
    	$model || $this->error('模型不存在！');

    	if(IS_POST){
    		$Model  =   D(parse_name(get_table_name($model['id']),1));
            // 获取模型的字段信息
    		$Model  =   $this->checkAttr($Model,$model['id']);
            //保存会员填写信息
            $viporder['name'] = $_POST['viprecord_name']?$_POST['viprecord_name']:null;
            $viporder['gender'] = $_POST['viprecord_gender']?$_POST['viprecord_gender']:null;
            $viporder['phone'] = $_POST['viprecord_phone']?$_POST['viprecord_phone']:null;
            $viporder['email'] = $_POST['viprecord_email']?$_POST['viprecord_email']:null;
            $viporder['idcard'] = $_POST['viprecord_idcard']?$_POST['viprecord_idcard']:null;
            $viporder['studentcard'] = $_POST['viprecord_studentcard']?$_POST['viprecord_studentcard']:null;
            $viporder['school'] = $_POST['viprecord_school']?$_POST['viprecord_school']:null;
            $viporder['edu'] = $_POST['viprecord_edu']?$_POST['viprecord_edu']:null;
            $viporder['job'] = $_POST['viprecord_job']?$_POST['viprecord_job']:null;
            $viporder['family_num'] = $_POST['viprecord_family_num']?$_POST['viprecord_family_num']:null;
            $viporder['focustype'] = $_POST['viprecord_focustype']?$_POST['viprecord_focustype']:null;

            $res = M('viprecord')->where(array('uid'=>$_POST['id']))->save($viporder);
    		if(($Model->create() && $Model->save())||$res){
                if($viporder['idcard']){
                    $this->success('保存'.$model['title'].'成功！', U('viplists?model='.$model['name']));
                }else{
                    $this->success('保存'.$model['title'].'成功！', U('lists?model='.$model['name']));
                }
    			
    		} else {
    			$this->error($Model->getError());
    		}
    	} else {
    		$fields     = get_model_attribute($model['id']);

            //获取数据
    		$data       = M(get_table_name($model['id']))->find($id);
    		$data || $this->error('数据不存在！');

            $uid = I('get.id');
            $orders = M('ticket_order')
            ->field('ticket_order.*,exhibition.name as ex_name,ticket.name as ticket_name')
            ->where(array('visitor_id'=>$uid))
            ->join('ticket on ticket.id = ticket_order.ticket_id','left')
            ->join('exhibition on exhibition.id = ticket.exhibition_id','left')
            ->order('ticket_order.create_time desc')
            ->select();

            foreach ($orders as $key => $value) {
                # code...
                $orders[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
            }

            if($data['vipcode']){
                $re_viprecord = M('viprecord')->where(array('uid'=>$uid))->find();
                $re_viporder = M('vip_order')
                ->field('vip_order.*,membership.title as membership_title')
                ->where(array('visitor_id'=>$uid,'vip_order.status'=>1))
                ->join('membership on membership.id = vip_order.vip_type','left')
                ->order('end_time desc')
                ->find();
            }
    		$this->assign('model', $model);
    		$this->assign('fields', $fields);
    		$this->assign('data', $data);
            $this->assign('orders', $orders);
            $this->assign('viprecord', $re_viprecord);
            $this->assign('viporder', $re_viporder);
    		$this->meta_title = '编辑'.$model['title'];
    		$this->display($model['template_edit']?$model['template_edit']:'');
    	}
    }

    public function add($model = null){
        //获取模型信息
    	$model = M('Model')->where(array('status' => 1))->find($model);
    	$model || $this->error('模型不存在！');
    	if(IS_POST){
    		$Model  =   D(parse_name(get_table_name($model['id']),1));
            // 获取模型的字段信息
    		$Model  =   $this->checkAttr($Model,$model['id']);
    		if($Model->create() && $Model->add()){
    			$this->success('添加'.$model['title'].'成功！', U('lists?model='.$model['name']));
    		} else {
    			$this->error($Model->getError());
    		}
    	} else {

    		$fields = get_model_attribute($model['id']);

    		$this->assign('model', $model);
    		$this->assign('fields', $fields);
    		$this->meta_title = '新增'.$model['title'];
    		$this->display($model['template_add']?$model['template_add']:'');
    	}
    }
  }